package org.doubango.FrCall.Screens.chat;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.doubango.FrCall.FrCall;
import org.doubango.FrCall.OpenfireNetService;
import org.doubango.FrCall.R;
import org.doubango.FrCall.Screens.BaseScreen;
import org.doubango.FrCall.Screens.ScreenHome;
import org.doubango.FrCall.Utils.DateTimeUtils;
import org.doubango.FrCall.Utils.DialogUtil;
import org.doubango.FrCall.Utils.LogDebugger;
import org.doubango.FrCall.Utils.RosterStoreManager;
import org.doubango.FrCall.model.RecentRoster;
import org.doubango.FrCall.model.User;
import org.doubango.ngn.media.NgnMediaType;
import org.doubango.ngn.model.NgnHistoryEvent;
import org.doubango.ngn.model.NgnHistoryEvent.StatusType;
import org.doubango.ngn.model.NgnHistorySMSEvent;
import org.doubango.ngn.services.INgnHistoryService;
import org.doubango.ngn.utils.NgnListUtils;
import org.doubango.ngn.utils.NgnPredicate;
import org.doubango.ngn.utils.NgnStringUtils;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;

public class ScreenChat extends BaseScreen {
	private static String TAG = ScreenChat.class.getCanonicalName();

	public static ScreenChat instance;
	
	private final INgnHistoryService mHistorytService;

	private User user;
	private Chat newChat;
	
	private ScreenChatAdapter mAdapter;
	private EditText mEtCompose;
	private ListView mLvHistoy;
	private Button mBtSend;
	private Button mBtSendFile;
	private Button mBtIcon;
	private TextView mTitleName;
	private Button mCancel;
	private SlidingDrawer inputArea;
	private GridView menuGrid;
	
	private Gallery mGallery;
	private ImageAdapter mImageAdapter;
	public static List<User> mAllUserList = new ArrayList<User>();
	public static int mCurrentIndex;
	
	public static List<NgnHistoryEvent> currentChatList = new ArrayList<NgnHistoryEvent>();
	
	private Handler mHandler;
	
	public ScreenChat() {
		super(SCREEN_TYPE.CHAT_T, TAG);
		mHistorytService = getEngine().getHistoryService();
		instance = this;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_chat);
		user = ScreenHome.selFriend;
		rosterDB = new RosterStoreManager(this);
		mEtCompose = (EditText) findViewById(R.id.screen_chat_editText_compose);
		mEtCompose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (mInputMethodManager != null) {
					mInputMethodManager.showSoftInput(v, mInputMethodManager.SHOW_IMPLICIT);
				}
			}
		});
		mBtSend = (Button) findViewById(R.id.screen_chat_button_send);
		mBtIcon = (Button) findViewById(R.id.screen_chat_button_voice_call);
		mBtSendFile = (Button) findViewById(R.id.screen_chat_button_send_file);
		mTitleName = (TextView) findViewById(R.id.name);
//		mAvatar = (ImageView) findViewById(R.id.avatar);
		mCancel = (Button) findViewById(R.id.cancel);
		mLvHistoy = (ListView) findViewById(R.id.screen_chat_listView);
		
		mAdapter = new ScreenChatAdapter(this);
		mGallery = (Gallery)findViewById(R.id.gallery);
		mImageAdapter = new ImageAdapter(this);
		
		mHandler = new Handler();
		
		refresh(-1);
		
		mLvHistoy.setAdapter(mAdapter);
//		mLvHistoy.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
//		mLvHistoy.setStackFromBottom(!true);			
		mLvHistoy.bringToFront();
		mGallery.setAdapter(mImageAdapter);
		mGallery.setSpacing(0);
        // 选择监听
		mGallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
//                Toast.makeText(ScreenChat.this, "" + position, Toast.LENGTH_SHORT).show();
                refresh(position);
            }
        });
		
//		menuGrid = (GridView)findViewById(R.id.screen_chat_emotion_grid);
//		menuGrid.setAdapter(getMenuAdapter(this.getResources().getStringArray(
//                R.array.default_smiley_name), Smileys.sIconIds));
//		/** 监听menu选项 **/
//		menuGrid.setOnItemClickListener(new OnItemClickListener() {
//			public void onItemClick(AdapterView<?> adV, View v, int pos,
//					long id) {
//				String str = ScreenChat.this.getResources().getStringArray(R.array.default_smiley_name)[pos];
//				mEtCompose.append(parser.addSmileySpans(str));
//				menuDialog.dismiss();
////				switch (arg2) {
////				case MENU_REFRESH_LIST:
////					if(roster!=null)
////						roster.reload();
////					break;
////				case MENU_ABOUT:
////					mScreenService.show(ScreenAbout.class, null, "关于");
////					menuDialog.dismiss();
////					break;
////				case MENU_EXIT:
////					((Main) getEngine().getMainActivity()).exit();
////					menuDialog.dismiss();
////					break;
////				case MENU_SETTINGS:
////					// Intent intent1 = new Intent(BaseScreen.this,
////					// ScreenSimpleSetting.class);
////					// startActivityForResult(intent1,0);
////					mScreenService
////							.show(ScreenSimpleSetting.class, null, "网络设置");
////					menuDialog.dismiss();
////					break;
////				}
//			}
//		});
		inputArea = (SlidingDrawer) findViewById(R.id.screen_chat_input_area);
		inputArea.lock();
//		inputArea.setOnTouchListener(new OnTouchListener() {
//			
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				return false;
//			}
//		});
//		inputArea.setOnDrawerOpenListener(new OnDrawerOpenListener() {
//			
//			@Override
//			public void onDrawerOpened() {
//				inputArea.bringToFront();
//			}
//		});
//		inputArea.setOnDrawerCloseListener(new OnDrawerCloseListener() {
//			
//			@Override
//			public void onDrawerClosed() {
//				mLvHistoy.bringToFront();
//			}
//		});
//		inputArea.setOnDrawerScrollListener(new OnDrawerScrollListener() {
//			
//			@Override
//			public void onScrollStarted() {
//				inputArea.bringToFront();
//			}
//			
//			@Override
//			public void onScrollEnded() {
//				// TODO Auto-generated method stub
//				
//			}
//		});
		mCancel.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				back();
			}
		});
		
		mBtIcon.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
//				mInputMethodManager.showSoftInput(menuGrid, 0);
				inputArea.animateToggle();
				if (mInputMethodManager != null) {
					mInputMethodManager.hideSoftInputFromWindow(
							mEtCompose.getWindowToken(), 0);
				}
			}
		});

		mBtSend.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!NgnStringUtils.isNullOrEmpty(mEtCompose.getText()
						.toString())) {
					sendMessage();
				}
				if(inputArea.isOpened())
					inputArea.animateClose();
				if (mInputMethodManager != null) {
					mInputMethodManager.hideSoftInputFromWindow(
							mEtCompose.getWindowToken(), 0);
				}
			}
		});
		
		mBtSendFile.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				selectFile();
			}
		});

		mEtCompose.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				mBtSend.setEnabled(!NgnStringUtils.isNullOrEmpty(mEtCompose
						.getText().toString()));
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		mEtCompose.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_UP:
					if (!v.hasFocus()) {
						v.requestFocus();
					}
					break;
				}
				return false;
			}
		});	
		
		// TODO
		// selectFile();
	}

	private SimpleAdapter getMenuAdapter(String[] menuNameArray,
			int[] imageResourceArray) {
		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < menuNameArray.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("itemImage", imageResourceArray[i]);
			map.put("itemText", "");
			data.add(map);
		}
		SimpleAdapter simperAdapter = new SimpleAdapter(this, data,
				R.layout.screen_home_item, new String[] { "itemImage",
						"itemText" }, new int[] { R.id.screen_home_item_icon,
						R.id.screen_home_item_text });
		return simperAdapter;
	}
	
	private ChatManager cm;
	
	public void refresh(int position) {	
		
		if (position == -1) {
			user = ScreenHome.selFriend;
			for (int i = 0; i < mAllUserList.size(); i++) {
				if (mAllUserList.get(i).getUserId().equals(user.getUserId())) {
					position =i;
					break;
				}
			}			
			if (position == -1) {
				mAllUserList.add(user);
				position = mAllUserList.size() - 1;	
			}			
		} else {
			user = mAllUserList.get(position);
		}

		mCurrentIndex = position;		
		
		mAdapter.refresh();
		mImageAdapter.refresh();
		
		cm = mOpenfireService.getXMPPConnection().getChatManager();
		newChat = cm.createChat(user.getUserId(), null);
		
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				mTitleName.setText(user.getUserId());
			}
		});
	}

	/**
	 * 服务器消息更新
	 */
	public void refreshFromServer() {		
		new refreshList().execute("");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		refresh(-1);
	}

	@Override
	protected void onPause() {
		if (mInputMethodManager != null) {
			mInputMethodManager.hideSoftInputFromWindow(
					mEtCompose.getWindowToken(), 0);
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean hasBack() {
		return true;
	}
//	@Override
//	public void onBackPressed() {
//
//		if(inputArea.isOpened())
//		{
//			inputArea.animateClose();
//			return;
//		}
//		super.onBackPressed();
//	}
	@Override
	public boolean back() {
		if(inputArea.isOpened())
		{
			inputArea.animateClose();
			return true;
		}
		boolean ret = mScreenService.back();
//		if (ret) {
//			finish();
//			mScreenService.back();
//		}
		return true;
	}

	/**
	 * 传送记录
	 */
	private void sendFileHistory(String content) {
		NgnHistorySMSEvent e = new NgnHistorySMSEvent(user.getUserId(), StatusType.Outgoing);
		e.setContent(content);
		mHistorytService.addEvent(e);
		currentChatList.add(e);
		refresh(mCurrentIndex);
	}
	
	/**
	 * 发消息
	 */
	private boolean sendMessage() {
		boolean ret = false;
		final String content = mEtCompose.getText().toString();
		final NgnHistorySMSEvent e = new NgnHistorySMSEvent(user.getUserId(),
				StatusType.Outgoing);
		e.setContent(content);
		currentChatList.add(e);
		mHistorytService.addEvent(e);
		mEtCompose.setText(NgnStringUtils.emptyValue());
		try {
			newChat.sendMessage(content);
		} catch (XMPPException e1) {
			Toast.makeText(getApplicationContext(), e1.getXMPPError().toString(), Toast.LENGTH_SHORT).show();
		} catch (Exception e2)
		{
			Toast.makeText(getApplicationContext(), e2.getMessage(), Toast.LENGTH_SHORT).show();
		}
		refresh(mCurrentIndex);
		RecentRoster recent = new RecentRoster(FrCall.user.getUserId(),selFriend.getUserId());
		recent.setRecentMessage(content);
		rosterDB.insert(recent);
//		RosterEntry friend = roster.getEntry(selFriend.getUserId());
//		RosterGroup group = roster.getGroup("最近联系人");
//    	if(group == null)
//    		roster.createGroup("最近联系人");
//    	group = roster.getGroup("最近联系人");
//    	try {
//			group.addEntry(friend);
//		} catch (XMPPException e3) {
//			e3.printStackTrace();
//		}
		return ret;
	}	
	
	/**
	 * HistoryEventSMSFilter
	 */
	class HistoryEventChatFilter implements NgnPredicate<NgnHistoryEvent> {
		@Override
		public boolean apply(NgnHistoryEvent event) {
			if (event != null && (event.getMediaType() == NgnMediaType.SMS)) {
				return NgnStringUtils.equals(user.getUserId(), event.getRemoteParty(), false);
			}
			return false;
		}
	}

	/**
	 * DateComparator
	 */
	class DateComparator implements Comparator<NgnHistoryEvent> {
		@Override
		public int compare(NgnHistoryEvent e1, NgnHistoryEvent e2) {
			return (int) (e1.getStartTime() - e2.getStartTime());
		}
	}
	
	public class refreshList extends AsyncTask<Object, Object, Object>
	{

		@Override
		protected Object doInBackground(Object... params) {
//			mAdapter.refresh();
			mImageAdapter.refresh();		
			return null;
		}
		
	}
	/**
	 * ScreenChatAdapter
	 */
	class ScreenChatAdapter extends BaseAdapter implements Observer {
		private List<NgnHistoryEvent> mChatList;
		private final LayoutInflater mInflater;
		private final Handler mHandler;
		private final ScreenChat mBaseScreen;

		ScreenChatAdapter(ScreenChat baseSceen) {
			mBaseScreen = baseSceen;
			mHandler = new Handler();
			mInflater = LayoutInflater.from(mBaseScreen);
			// 用户过滤
			mChatList = NgnListUtils.filter(currentChatList , new HistoryEventChatFilter());
			// 时间排序
			Collections.sort(mChatList, new DateComparator());	
			
			mBaseScreen.mHistorytService.getObservableEvents().addObserver(this);
		}

		@Override
		protected void finalize() throws Throwable {
			mBaseScreen.mHistorytService.getObservableEvents().deleteObserver(
					this);
			super.finalize();
		}

		public void refresh() {			
			// 用户过滤
			mChatList = NgnListUtils.filter(currentChatList , new HistoryEventChatFilter());
			// 时间排序
			Collections.sort(mChatList, new DateComparator());			
			
			if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
				notifyDataSetChanged();
			} else {
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						notifyDataSetChanged();
					}
				});
			}
		}

		@Override
		public int getCount() {
			return mChatList.size();
		}

		@Override
		public Object getItem(int position) {
			return mChatList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public boolean isEnabled(int position) {
			return false;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.screen_chat_item, null, false);
				holder = new ViewHolder();
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				holder.text = (TextView) convertView.findViewById(R.id.text);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final NgnHistoryEvent event = (NgnHistoryEvent) getItem(position);

			final NgnHistorySMSEvent SMSEvent = (NgnHistorySMSEvent) event;
			final String content = SMSEvent.getContent();
			final boolean bIncoming = SMSEvent.getStatus() == StatusType.Incoming;
			
			int color;
			String name;
			if (bIncoming) {
				color = 0xFF005aa7;
				name = mBaseScreen.user.getDisplayName();
			} else {
				color = 0xFF63a003;
				name = "我";
			}
			holder.name.setText(name);
			holder.name.setTextColor(color);
			holder.time.setText(DateTimeUtils.getFriendlyDateString(new Date(event.getStartTime())));
//			holder.text.setText(parser.addSmileySpans(content));
			holder.text.setText(content);
			return convertView;
		}

		@Override
		public void update(Observable observable, Object data) {
			refresh();
		}

		private class ViewHolder {
			TextView name;
			TextView time;
			TextView text;
		}
	}
	
	public class ImageAdapter extends BaseAdapter {
     
		private List<User> mUserList;
		private final LayoutInflater mInflater;
		private final Handler mHandler;
		private final ScreenChat mBaseScreen;
        
        public ImageAdapter(ScreenChat baseScreen) {
        	mBaseScreen = baseScreen;
			mHandler = new Handler();
			mInflater = LayoutInflater.from(mBaseScreen);
        }
        
		public void refresh() {
			
			mUserList = mAllUserList;
			
			if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
				notifyDataSetChanged();
			} else {
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						notifyDataSetChanged();
					}
				});
			}
		}

        public int getCount() {
        	return mUserList.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
       	
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.screen_chat_title_item, null, false);
				holder = new ViewHolder();
				holder.bg = (ImageView) convertView.findViewById(R.id.avatar_bg);
//				holder.avatar = (ImageView) convertView.findViewById(R.id.avatar);
				convertView.setTag(holder);
				convertView.setLayoutParams(new Gallery.LayoutParams(100, 65));
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
//			if (mCurrentIndex == position) {
//				holder.bg.setVisibility(View.VISIBLE);
//			} else {
//				holder.bg.setVisibility(View.INVISIBLE);
//			}
//			Bitmap bm = mUserList.get(position).getAvatar();
//			holder.avatar.setImageBitmap(bm);
			return convertView;
        }

		private class ViewHolder {
			ImageView bg;
			ImageView avatar;;
		}
    }
	

	/**
	 * 选择文件
	 */
    private void selectFile()
    {
    	Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    	//能打开的文件
    	intent.addCategory(Intent.CATEGORY_OPENABLE);
    	intent.setType("*/*");
    	intent.putExtra("return-data", true);
    	Intent intent1 = Intent.createChooser(intent, "选择文件");
    	startActivityForResult(intent1, ACTIVITY_SELECT_FILE);
    }
    
    public static final int ACTIVITY_CAMERA = 200;
    public static final int ACTIVITY_SELECT_FILE = 201;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 
    	if(resultCode == RESULT_CANCELED)
    	{
    		return;
    	}	
    	File file;
    	switch(requestCode)
    	{
    	    case ACTIVITY_CAMERA: // 数据是放在额外data返回的
    	    	Bundle localBundle = intent.getExtras();
    	    	if(localBundle == null)
    	    	{
    	    		LogDebugger.debug(TAG, "no extended data");
    	    		return;
    	    	}
    	    	file = (File)localBundle.get("data");
    	    	sendFile(file);
    	    	break;
    	    case ACTIVITY_SELECT_FILE: // 数据是以URI形式放回的。
    	    	Uri uri = intent.getData(); 
    	    	if (uri == null) {
    	    		Toast.makeText(ScreenChat.this, "返回数据错误", Toast.LENGTH_SHORT).show();
    	    	} else {
        	    	file = new File(getPath(uri));  
        	    	sendFile(file);
    	    	}

    	    	break;
    	}
    	super.onActivityResult(requestCode, resultCode, intent);
    }
    
    public static final int HANDLER_TOAST = 0;
    public static final int HANDLER_SENDING = 1;
    
    private static final int MAX_PROGRESS = 100;
    
    public String sToastMsg;    
    private ProgressDialog mProgressDialog;
    private int mProgress;
    
    private Handler handler = new Handler() {
    	
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HANDLER_TOAST:
				Toast.makeText(ScreenChat.this, sToastMsg, Toast.LENGTH_SHORT).show();
				break;
				
			case HANDLER_SENDING:
				if (mProgressDialog == null) {
					mProgressDialog = new ProgressDialog(ScreenChat.this);
					mProgressDialog.setIcon(R.drawable.jia);
					mProgressDialog.setTitle("传送文件中...");
					mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					mProgressDialog.setMax(MAX_PROGRESS);
					mProgressDialog.setCancelable(false);										
				}
				mProgressDialog.setProgress(0);
				mProgressDialog.show();
				break;
				
			default:
				break;
			}
		}
	
    };

	/**
	 * 发送文件
	 */
	private void sendFile(final File file) {
		
//		if (file.length() > 200 * 1024) {
//			Toast.makeText(this, "目前仅支持发送200K以下的文件，谢谢！", Toast.LENGTH_LONG).show();
//			return;
//		}
		
		String toUser = user.getJID();
		Log.v("sendFile", "send file to "+toUser);
		XMPPConnection conn = OpenfireNetService.getXMPPConnection();

		FileTransferManager manager = new FileTransferManager(conn);
		final OutgoingFileTransfer transfer = manager
				.createOutgoingFileTransfer(toUser);
		OutgoingFileTransfer.setResponseTimeout(5000);
		try {
			transfer.sendFile(file, "data backup");
		} catch (XMPPException e1) {
			e1.printStackTrace();
		}
		
		final Dialog dialog = DialogUtil.openMsgDialog(
				ScreenChat.this,
				R.drawable.jia,
				"等待对方接受",
				"取消",				
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(
							DialogInterface dialog,
							int which) {
						// 取消
						transfer.cancel();
					}
				});
		dialog.setCancelable(false);
		dialog.show();				
		
		new Thread () {
			public void run() {
				
				FileTransfer.Status temp = null;
				
				while(true) {
					
					if (temp != transfer.getStatus()) {
						temp = transfer.getStatus();
						LogDebugger.debug(TAG, "传送文件当前状态：" + temp);
					}					
					
					if (transfer.getStatus() == FileTransfer.Status.cancelled) {
						sToastMsg = "您取消了文件发送";
						handler.sendEmptyMessage(HANDLER_TOAST);
						dialog.cancel();
						String history = "您取消了" +"\"" + file.getName() + "\"(" + file.length() + "byte)的发送,文件传输失败。";
						sendFileHistory(history);
						break;
						
					} else if (transfer.getStatus() == FileTransfer.Status.refused) {
						sToastMsg = "对方拒绝接受文件";
						handler.sendEmptyMessage(HANDLER_TOAST);
						dialog.cancel();
						String history = "对方拒绝了" +"\"" + file.getName() + "\"(" + file.length() + "byte)的传送,文件传输失败。";
						sendFileHistory(history);
						break;
						
					} else if (transfer.getStatus() == FileTransfer.Status.error) {
						sToastMsg = "发送文件出现异常";
						handler.sendEmptyMessage(HANDLER_TOAST);
						dialog.cancel();
						String history = "发送" +"\"" + file.getName() + "\"(" + file.length() + "byte)出现异常,文件传输失败。";
						sendFileHistory(history);
						break;
						
					} else if (transfer.getStatus() == FileTransfer.Status.negotiating_stream) {
						handler.sendEmptyMessage(HANDLER_SENDING);
						dialog.cancel();
						
					} else if (transfer.getStatus() == FileTransfer.Status.in_progress) {
						LogDebugger.debug(TAG, "传送文件当前状态：" + transfer.getProgress());
						// 接受文件中...
						mProgress = (int)(transfer.getProgress() * 100);
						mProgressDialog.setProgress(mProgress);	
						
					} else if (transfer.getStatus() == FileTransfer.Status.complete) {
						sToastMsg = "成功发送文件";
						handler.sendEmptyMessage(HANDLER_TOAST);
						mProgressDialog.cancel();
						String history = sToastMsg +"\"" + file.getName() + "\"(" + file.length() + "byte)";
						sendFileHistory(history);
						break;
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
}
